package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-08-08
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin//跨域
public class OrderController {

    @Autowired
    private OrderService orderService;

    //生成订单的方法
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest reques) {

        //创建订单，返回订单号
        String token = JwtUtils.getMemberIdByJwtToken(reques);
        System.out.println("创建订单号方法被调用了");
        System.out.println("其中课程id->courseId：" + courseId + "用户id->reques：" + token);
        String orderNo = orderService.createOrders(courseId,JwtUtils.getMemberIdByJwtToken(reques));
        return R.ok().data("orderId",orderNo);
    }

    //根据订单id，查询订单的信息
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        System.out.println("讲师名称"+order.getTeacherName());
        return R.ok().data("item",order);
    }

    //根据课程id和用户id查询订单表中的订单状态
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);//count:能不能查出记录
        /*if(count == 0) {
            System.out.println("数据库中此用户没有购买记录");
            return false;
        }else {
            return true;
        }*/

        return count>0;

    }

}

